package org.csu.mypetstore.domain;

import com.alibaba.fastjson.*;
import okhttp3.*;
import java.io.*;

public class UploadUtil {
    public static JSONObject uploadImg(File image, String apiType, String privateStorage, String token, String url) {
        RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"), image);
        OkHttpClient client = new OkHttpClient();
        JSONObject jsonObject = null;
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image", image.getName(), fileBody)
                .addFormDataPart("apiType", apiType)
                .addFormDataPart("privateStorage", privateStorage)
                .addFormDataPart("token", token)
                .build();

        System.out.println(requestBody.toString());
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        Response response;
        try {
            response = client.newCall(request).execute();
            String jsonString = response.body().string();
            jsonObject = JSON.parseObject(jsonString);

            if(!jsonObject.getString("code").equals("200")){
                System.out.println("失败");
            }else{

            }

        } catch (IOException e) {

        }catch (JSONException e){

        }
        return jsonObject;
    }

    //获取流文件
    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
